class BillsController < ApplicationController
  before_action :login_auth
  def index
    @bills = Bill.all
  end

  def show
    @bill = Bill.find(params[:id])
  end

  def edit
    @bill = Bill.find(params[:id])
    @group_users = Group.find(@bill.group_id).users
    @edit_tag = true
    @member_ids = one_bill_users_ids(@bill)
    Rails.logger.debug @member_ids
  end

  def new
    @bill = Bill.new
    redirect_to groups_path unless current_user.group_id
    @group = Group.find(current_user.group_id)
    @group_users = @group.users
  end

  def create
    # Rails.logger.debug "params = #{params}"
    users = params[:bill][:members].keys
    @bill = Bill.new(bill_params)
    @bill.user_id = current_user.id
    @bill.group_id = current_group.id
    @bill.status = 0
    users.each do |user_id|
      @bill.containers.build(user_id: user_id.to_i)
    end
    if @bill.save
      flash[:notice] = "bill saved success!"
    else
      flash[:notice] = "bill saved failed!"
      redirect_to new_bill_path
      return
    end
    @users ||= []
    @bill.bill_members.each {|user| users << user.id}
    BillsMail.bills_notify(@bill).deliver_later
    redirect_to user_bills_page_path
  end

  def update
    old_bill = Bill.find(params[:id])
    # old_bill.restore_one_bill
    member_ids = []
    params[:bill][:members].keys.each do |user_id|
      # Container.create(bill_id: old_bill.id, user_id: user_id)
      member_ids << user_id.dup
    end
    old_bill.update_one_bill(bill_params, member_ids)
    flash[:notice] = "bill update success!"
    redirect_to user_bills_page_path
  end

  def destroy
  end
  private
  def bill_params
    params.require(:bill).permit(:name, :description, :amount)
  end
end
